package com.white.algebra.controller;

import com.white.algebra.domain.Syslog;
import com.white.algebra.domain.UserInfo;
import com.white.algebra.service.SysLogService;
import com.white.algebra.service.UserService;
import com.white.algebra.service.impl.SysLogServiceImpl;
import com.white.algebra.service.impl.UserServiceImpl;
import com.white.algebra.utils.MqUtils;

import javax.jms.JMSException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Date;
@MultipartConfig    //标识Servlet支持文件上传
public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String action=req.getParameter("action");
//        System.out.println("--"+action+"--");
        String ip = req.getRemoteAddr();
        Date visitTime = new Date();
        String url = req.getRequestURI();
        Syslog sysLog=new Syslog();
        sysLog.setIp(ip);
        sysLog.setMethod(action);
        sysLog.setUrl(url);
        sysLog.setVisitTime(visitTime);
        try {
            Method method=this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }finally {
            Date endTime = new Date();
            //访问时长
            long time = endTime.getTime() - visitTime.getTime();
            sysLog.setExecutionTime(time);
            if(!"logout".equals(action)){
                UserInfo userInfo = (UserInfo) req.getSession().getAttribute("user");
                String username=null;
                if(userInfo!=null){
                    username=userInfo.getUsername();
                }
                sysLog.setUsername(username);
            }else {
                sysLog.setUsername(null);
            }
            try {
                MqUtils.sendQueueMessage(sysLog);
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }

}
